<template>
  <div class="game-container">
    <div class="game-header">
      <button 
        v-if="keySettings.showBackButton" 
        class="back-button" 
        @click="goBack" 
        tabindex="0" 
        ref="backButton"
      >
        返回
      </button>
      <h1 class="game-title">成语接龙</h1>
    </div>
    
    <div class="game-content">
      <div class="idiom-card">
        <div class="score-display">
          <div class="score">得分: {{ score }}</div>
          <div class="timer">时间: {{ timeLeft }}秒</div>
        </div>
        
        <div class="current-idiom" v-if="currentIdiom">
          <h2>当前成语:</h2>
          <div class="idiom-text">{{ currentIdiom }}</div>
          <div class="next-char">下一个成语需以 "{{ nextChar }}" 开头</div>
        </div>
        
        <div class="input-area">
          <div class="options-container">
            <button 
              v-for="(option, index) in currentOptions" 
              :key="index"
              class="option-button"
              :class="{ 'selected': selectedOptionIndex === index }"
              @click="selectOption(index)"
              tabindex="0"
              ref="optionButtons"
            >
              {{ option }}
            </button>
          </div>
        </div>
        
        <div class="message" v-if="message">{{ message }}</div>
        
        <div class="history-container" v-if="idiomHistory.length > 0">
          <h3>成语历史:</h3>
          <div class="history-list">
            <div v-for="(idiom, index) in idiomHistory" :key="index" class="history-item">
              {{ index + 1 }}. {{ idiom }}
            </div>
          </div>
        </div>
        
        <div class="controls">
          <button 
            class="control-button hint-button" 
            @click="getHint"
            tabindex="0"
            ref="hintButton"
          >
            提示
          </button>
          
          <button 
            class="control-button next-button" 
            @click="confirmSelection"
            tabindex="0"
            ref="confirmButton"
          >
            确认
          </button>
        </div>
      </div>
    </div>
    
    <div class="game-over-modal" v-if="isGameOver">
      <div class="modal-content">
        <h2>游戏结束</h2>
        <p>你的最终得分: {{ score }}</p>
        <button class="restart-button" @click="restartGame" tabindex="0" ref="restartButton">重新开始</button>
        <button class="home-button" @click="goBack" tabindex="0">返回主页</button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onBeforeUnmount } from 'vue';
import { useRouter } from 'vue-router';
import { getKeySettings, setupGlobalKeyHandlers, type KeySettings } from '../utils/keySettings';

const router = useRouter();

// 按键设置
const keySettings = reactive<KeySettings>({
  showBackButton: true,
  enableEscapeKey: true,
  enableContextMenu: true,
  enableKeyboardNavigation: true
});

const backButton = ref<HTMLElement | null>(null);
const hintButton = ref<HTMLElement | null>(null);
const confirmButton = ref<HTMLElement | null>(null);
const optionButtons = ref<HTMLElement[]>([]);
const restartButton = ref<HTMLElement | null>(null);

// 成语数据库
const idiomDatabase = [
  { text: "一帆风顺", firstChar: "一", lastChar: "顺" },
  { text: "顺水推舟", firstChar: "顺", lastChar: "舟" },
  { text: "舟车劳顿", firstChar: "舟", lastChar: "顿" },
  { text: "顿开茅塞", firstChar: "顿", lastChar: "塞" },
  { text: "塞翁失马", firstChar: "塞", lastChar: "马" },
  { text: "马到成功", firstChar: "马", lastChar: "功" },
  { text: "功成名就", firstChar: "功", lastChar: "就" },
  { text: "就地取材", firstChar: "就", lastChar: "材" },
  { text: "材高八斗", firstChar: "材", lastChar: "斗" },
  { text: "斗志昂扬", firstChar: "斗", lastChar: "扬" },
  { text: "扬长避短", firstChar: "扬", lastChar: "短" },
  { text: "短兵相接", firstChar: "短", lastChar: "接" },
  { text: "接二连三", firstChar: "接", lastChar: "三" },
  { text: "三心二意", firstChar: "三", lastChar: "意" },
  { text: "意气风发", firstChar: "意", lastChar: "发" },
  { text: "发扬光大", firstChar: "发", lastChar: "大" },
  { text: "大公无私", firstChar: "大", lastChar: "私" },
  { text: "私心杂念", firstChar: "私", lastChar: "念" },
  { text: "念念不忘", firstChar: "念", lastChar: "忘" },
  { text: "忘乎所以", firstChar: "忘", lastChar: "以" },
  { text: "以逸待劳", firstChar: "以", lastChar: "劳" },
  { text: "劳无所获", firstChar: "劳", lastChar: "获" },
  { text: "获益匪浅", firstChar: "获", lastChar: "浅" },
  { text: "浅尝辄止", firstChar: "浅", lastChar: "止" },
  { text: "止于至善", firstChar: "止", lastChar: "善" },
  { text: "善始善终", firstChar: "善", lastChar: "终" },
  { text: "终成眷属", firstChar: "终", lastChar: "属" },
  { text: "属于自己", firstChar: "属", lastChar: "己" },
  { text: "己所不欲", firstChar: "己", lastChar: "欲" },
  { text: "欲罢不能", firstChar: "欲", lastChar: "能" }
];

// 游戏状态
const currentIdiom = ref("");
const nextChar = ref("");
const score = ref(0);
const timeLeft = ref(60);
const timer = ref<number | null>(null);
const idiomHistory = ref<string[]>([]);
const usedIdioms = ref<Set<string>>(new Set());
const message = ref("");
const isGameOver = ref(false);
const currentOptions = ref<string[]>([]);
const selectedOptionIndex = ref(-1);

// 初始化游戏
const initGame = () => {
  // 随机选择一个成语作为起始成语
  const randomIndex = Math.floor(Math.random() * idiomDatabase.length);
  const startIdiom = idiomDatabase[randomIndex].text;
  
  currentIdiom.value = startIdiom;
  nextChar.value = startIdiom.charAt(startIdiom.length - 1);
  
  idiomHistory.value = [startIdiom];
  usedIdioms.value = new Set([startIdiom]);
  
  // 生成选项
  generateOptions();
  
  // 重置游戏状态
  score.value = 0;
  timeLeft.value = 60;
  message.value = "";
  isGameOver.value = false;
  selectedOptionIndex.value = -1;
  
  // 启动计时器
  startTimer();
};

// 生成选项
const generateOptions = () => {
  // 找到所有以nextChar开头的成语
  const validOptions = idiomDatabase.filter(idiom => 
    idiom.firstChar === nextChar.value && !usedIdioms.value.has(idiom.text)
  );
  
  // 如果没有有效选项，游戏结束
  if (validOptions.length === 0) {
    endGame("没有更多可用的成语了！");
    return;
  }
  
  // 从有效选项中随机选择4个（或更少）
  const selectedOptions: string[] = [];
  const availableOptions = [...validOptions];
  
  // 添加1-3个干扰项（不以nextChar开头的成语）
  const invalidOptions = idiomDatabase.filter(idiom => 
    idiom.firstChar !== nextChar.value && !usedIdioms.value.has(idiom.text)
  );
  
  // 确保至少有一个正确选项
  if (availableOptions.length > 0) {
    const correctOption = availableOptions.splice(Math.floor(Math.random() * availableOptions.length), 1)[0];
    selectedOptions.push(correctOption.text);
  }
  
  // 添加干扰项，总共不超过4个选项
  while (selectedOptions.length < 4 && invalidOptions.length > 0) {
    const randomIndex = Math.floor(Math.random() * invalidOptions.length);
    selectedOptions.push(invalidOptions.splice(randomIndex, 1)[0].text);
  }
  
  // 如果还有空间，添加更多正确选项
  while (selectedOptions.length < 4 && availableOptions.length > 0) {
    const randomIndex = Math.floor(Math.random() * availableOptions.length);
    selectedOptions.push(availableOptions.splice(randomIndex, 1)[0].text);
  }
  
  // 打乱选项顺序
  currentOptions.value = selectedOptions.sort(() => Math.random() - 0.5);
};

// 选择选项
const selectOption = (index: number) => {
  selectedOptionIndex.value = index;
};

// 确认选择
const confirmSelection = () => {
  if (selectedOptionIndex.value === -1) {
    message.value = "请选择一个成语";
    return;
  }
  
  const selectedIdiom = currentOptions.value[selectedOptionIndex.value];
  
  // 检查是否以正确的字开头
  if (selectedIdiom.charAt(0) !== nextChar.value) {
    message.value = `错误！成语必须以"${nextChar.value}"开头`;
    return;
  }
  
  // 检查是否已使用过
  if (usedIdioms.value.has(selectedIdiom)) {
    message.value = "这个成语已经用过了";
    return;
  }
  
  // 成功接龙
  currentIdiom.value = selectedIdiom;
  nextChar.value = selectedIdiom.charAt(selectedIdiom.length - 1);
  
  // 更新历史和已使用成语集合
  idiomHistory.value.push(selectedIdiom);
  usedIdioms.value.add(selectedIdiom);
  
  // 增加分数和时间
  score.value += 10;
  timeLeft.value += 5; // 每次成功接龙增加5秒
  
  // 清除消息
  message.value = "";
  
  // 生成新的选项
  generateOptions();
  selectedOptionIndex.value = -1;
};

// 获取提示
const getHint = () => {
  // 找到一个有效的成语作为提示
  const validIdioms = idiomDatabase.filter(idiom => 
    idiom.firstChar === nextChar.value && !usedIdioms.value.has(idiom.text)
  );
  
  if (validIdioms.length > 0) {
    const hintIdiom = validIdioms[Math.floor(Math.random() * validIdioms.length)].text;
    message.value = `提示: 可以使用 "${hintIdiom}"`;
    
    // 使用提示会减少分数
    if (score.value >= 5) {
      score.value -= 5;
    }
  } else {
    message.value = "没有更多可用的成语了！";
    endGame("没有更多可用的成语了！");
  }
};

// 启动计时器
const startTimer = () => {
  if (timer.value) {
    clearInterval(timer.value);
  }
  
  timer.value = setInterval(() => {
    if (timeLeft.value > 0) {
      timeLeft.value--;
    } else {
      endGame("时间到！");
    }
  }, 1000) as unknown as number;
};

// 结束游戏
const endGame = (reason: string) => {
  if (timer.value) {
    clearInterval(timer.value);
    timer.value = null;
  }
  
  message.value = reason;
  isGameOver.value = true;
  
  // 聚焦到重新开始按钮
  setTimeout(() => {
    restartButton.value?.focus();
  }, 100);
};

// 重新开始游戏
const restartGame = () => {
  initGame();
};

// 返回主页
const goBack = () => {
  if (timer.value) {
    clearInterval(timer.value);
    timer.value = null;
  }
  router.push('/');
};

// 键盘导航处理
const handleKeyDown = (event: KeyboardEvent) => {
  if (isGameOver.value) {
    // 游戏结束状态下的键盘导航
    if (event.key === 'ArrowUp' || event.key === 'ArrowDown') {
      if (document.activeElement === restartButton.value) {
        const homeButton = document.querySelector('.home-button') as HTMLElement;
        homeButton?.focus();
      } else {
        restartButton.value?.focus();
      }
    } else if (event.key === 'Enter') {
      if (document.activeElement === restartButton.value) {
        restartGame();
      } else if (document.activeElement?.classList.contains('home-button')) {
        goBack();
      }
    }
    return;
  }
  
  switch (event.key) {
    case 'ArrowUp':
      navigateFocus('up');
      break;
    case 'ArrowDown':
      navigateFocus('down');
      break;
    case 'ArrowLeft':
      navigateFocus('left');
      break;
    case 'ArrowRight':
      navigateFocus('right');
      break;
    case 'Enter':
      if (document.activeElement === backButton.value) {
        goBack();
      } else if (document.activeElement === hintButton.value) {
        getHint();
      } else if (document.activeElement === confirmButton.value) {
        confirmSelection();
      } else {
        // 检查是否是选项按钮
        const optionIndex = Array.from(optionButtons.value).findIndex(btn => btn === document.activeElement);
        if (optionIndex !== -1) {
          selectOption(optionIndex);
        }
      }
      break;
  }
};

// 焦点导航
const navigateFocus = (direction: 'up' | 'down' | 'left' | 'right') => {
  const activeElement = document.activeElement;
  
  // 选项按钮导航
  if (optionButtons.value.includes(activeElement as HTMLElement)) {
    const currentIndex = optionButtons.value.findIndex(btn => btn === activeElement);
    const optionsPerRow = 2; // 每行2个选项
    const currentRow = Math.floor(currentIndex / optionsPerRow);
    const currentCol = currentIndex % optionsPerRow;
    
    if (direction === 'up') {
      if (currentRow > 0) {
        // 向上导航到上一行的相同列
        const targetIndex = (currentRow - 1) * optionsPerRow + currentCol;
        if (targetIndex >= 0 && targetIndex < optionButtons.value.length) {
          optionButtons.value[targetIndex]?.focus();
        }
      } else {
        // 从第一行向上导航到返回按钮
        backButton.value?.focus();
      }
    } else if (direction === 'down') {
      if (currentRow < Math.floor((optionButtons.value.length - 1) / optionsPerRow)) {
        // 向下导航到下一行的相同列
        const targetIndex = (currentRow + 1) * optionsPerRow + currentCol;
        if (targetIndex < optionButtons.value.length) {
          optionButtons.value[targetIndex]?.focus();
        }
      } else {
        // 从最后一行向下导航到控制按钮
        if (currentCol === 0) {
          hintButton.value?.focus();
        } else {
          confirmButton.value?.focus();
        }
      }
    } else if (direction === 'left') {
      if (currentCol > 0) {
        // 向左导航到同一行的前一个选项
        optionButtons.value[currentIndex - 1]?.focus();
      }
    } else if (direction === 'right') {
      if (currentCol < optionsPerRow - 1 && currentIndex < optionButtons.value.length - 1) {
        // 向右导航到同一行的下一个选项
        optionButtons.value[currentIndex + 1]?.focus();
      }
    }
  } else if (activeElement === backButton.value) {
    if (direction === 'down') {
      // 从返回按钮向下导航到第一个选项
      optionButtons.value[0]?.focus();
    }
  } else if (activeElement === hintButton.value) {
    if (direction === 'up') {
      // 从提示按钮向上导航到最后一行的第一个选项
      const lastRowFirstOption = Math.floor((optionButtons.value.length - 1) / 2) * 2;
      optionButtons.value[lastRowFirstOption]?.focus();
    } else if (direction === 'right') {
      // 从提示按钮向右导航到确认按钮
      confirmButton.value?.focus();
    }
  } else if (activeElement === confirmButton.value) {
    if (direction === 'up') {
      // 从确认按钮向上导航到最后一行的最后一个选项
      optionButtons.value[optionButtons.value.length - 1]?.focus();
    } else if (direction === 'left') {
      // 从确认按钮向左导航到提示按钮
      hintButton.value?.focus();
    }
  }
};

// 加载按键设置的函数
const loadKeySettings = async () => {
  const settings = await getKeySettings();
  Object.assign(keySettings, settings);
};

// 页面获得焦点时重新加载设置
const handleVisibilityChange = () => {
  if (!document.hidden) {
    loadKeySettings();
  }
};

onMounted(async () => {
  // 初始加载按键设置
  await loadKeySettings();
  
  // 设置全局按键处理器
  const cleanup = setupGlobalKeyHandlers(keySettings, {
    onEscape: () => goBack(),
    onKeyDown: keySettings.enableKeyboardNavigation ? handleKeyDown : undefined
  });
  
  // 监听页面可见性变化，当页面重新获得焦点时重新加载设置
  document.addEventListener('visibilitychange', handleVisibilityChange);
  
  // 初始化游戏
  initGame();
  
  // 初始聚焦到返回按钮（如果显示的话）
  if (keySettings.showBackButton) {
    backButton.value?.focus();
  }
  
  // 组件卸载时清理
  onBeforeUnmount(() => {
    cleanup();
    document.removeEventListener('visibilitychange', handleVisibilityChange);
    
    // 清除计时器
    if (timer.value) {
      clearInterval(timer.value);
      timer.value = null;
    }
  });
});
</script>

<style scoped>
.game-container {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
  padding: 2rem;
  background-color: #121212;
  color: white;
}

.game-header {
  display: flex;
  align-items: center;
  margin-bottom: 2rem;
  position: relative;
}

.back-button {
  position: absolute;
  left: 0;
  padding: 0.75rem 1.5rem;
  background-color: #333;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 1.2rem;
  transition: background-color 0.3s;
}

.back-button:hover, .back-button:focus {
  background-color: #555;
  outline: 3px solid #4a90e2;
}

.game-title {
  width: 100%;
  text-align: center;
  font-size: 2.5rem;
  margin: 0;
}

.game-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  flex-grow: 1;
}

.idiom-card {
  background-color: #2a2a2a;
  border-radius: 16px;
  padding: 2rem;
  max-width: 800px;
  width: 100%;
  box-shadow: 0 10px 20px rgba(0, 0, 0, 0.3);
}

.score-display {
  display: flex;
  justify-content: space-between;
  margin-bottom: 2rem;
  font-size: 1.5rem;
}

.score, .timer {
  padding: 0.5rem 1rem;
  background-color: #333;
  border-radius: 8px;
}

.timer {
  color: #ff9800;
}

.current-idiom {
  text-align: center;
  margin-bottom: 2rem;
}

.idiom-text {
  font-size: 2.5rem;
  font-weight: bold;
  color: #4a90e2;
  margin: 1rem 0;
}

.next-char {
  font-size: 1.5rem;
  color: #ff9800;
}

.input-area {
  margin-bottom: 2rem;
}

.options-container {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 1.5rem;
}

.option-button {
  padding: 1.5rem;
  background-color: #333;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 1.5rem;
  transition: all 0.3s;
  text-align: center;
}

.option-button:hover, .option-button:focus {
  background-color: #444;
  transform: translateY(-5px);
  outline: 3px solid #4a90e2;
}

.option-button.selected {
  background-color: #4a90e2;
}

.message {
  text-align: center;
  margin: 1rem 0;
  padding: 1rem;
  background-color: rgba(255, 152, 0, 0.2);
  border-radius: 8px;
  color: #ff9800;
}

.history-container {
  margin-top: 2rem;
  max-height: 150px;
  overflow-y: auto;
  background-color: #333;
  border-radius: 8px;
  padding: 1rem;
}

.history-list {
  display: flex;
  flex-wrap: wrap;
  gap: 0.5rem;
}

.history-item {
  background-color: #444;
  padding: 0.5rem;
  border-radius: 4px;
}

.controls {
  display: flex;
  justify-content: space-between;
  margin-top: 2rem;
}

.control-button {
  padding: 1rem 2rem;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 1.2rem;
  transition: background-color 0.3s;
}

.hint-button {
  background-color: #555;
  color: white;
}

.hint-button:hover, .hint-button:focus {
  background-color: #666;
  outline: 3px solid #4a90e2;
}

.next-button {
  background-color: #4a90e2;
  color: white;
}

.next-button:hover, .next-button:focus {
  background-color: #3a80d2;
  outline: 3px solid #4a90e2;
}

.game-over-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 100;
}

.modal-content {
  background-color: #2a2a2a;
  border-radius: 16px;
  padding: 2rem;
  max-width: 500px;
  width: 100%;
  text-align: center;
}

.modal-content h2 {
  font-size: 2rem;
  margin-bottom: 1rem;
}

.modal-content p {
  font-size: 1.5rem;
  margin-bottom: 2rem;
}

.restart-button, .home-button {
  padding: 1rem 2rem;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 1.2rem;
  margin: 0 0.5rem;
  transition: all 0.3s;
}

.restart-button {
  background-color: #4a90e2;
  color: white;
}

.restart-button:hover, .restart-button:focus {
  background-color: #3a80d2;
  outline: 3px solid #4a90e2;
}

.home-button {
  background-color: #555;
  color: white;
}

.home-button:hover, .home-button:focus {
  background-color: #666;
  outline: 3px solid #4a90e2;
}

/* 响应式布局 */
/* 小屏幕适配 */
@media (max-height: 700px) {
  .game-container {
    padding: clamp(0.5rem, 2vw, 1.5rem);
  }
  
  .game-title {
    font-size: clamp(1.5rem, 4vw, 2rem);
  }
  
  .idiom-card {
    padding: clamp(1rem, 3vw, 1.5rem);
  }
  
  .score-display {
    font-size: clamp(1rem, 3vw, 1.2rem);
    margin-bottom: 1rem;
  }
  
  .idiom-text {
    font-size: clamp(1.5rem, 4vw, 2rem);
  }
  
  .next-char {
    font-size: clamp(1rem, 3vw, 1.2rem);
  }
  
  .option-button {
    padding: clamp(0.8rem, 2vw, 1.2rem);
    font-size: clamp(1rem, 3vw, 1.3rem);
  }
  
  .control-button {
    padding: clamp(0.8rem, 2vw, 1rem) clamp(1rem, 3vw, 1.5rem);
    font-size: clamp(1rem, 2.5vw, 1.1rem);
  }
}

@media (max-width: 768px) {
  .game-container {
    padding: clamp(0.5rem, 3vw, 1rem);
  }
  
  .game-header {
    margin-bottom: 1rem;
  }
  
  .back-button {
    padding: clamp(0.5rem, 2vw, 0.75rem) clamp(0.8rem, 3vw, 1.2rem);
    font-size: clamp(0.9rem, 3vw, 1.1rem);
  }
  
  .game-title {
    font-size: clamp(1.5rem, 5vw, 2rem);
  }
  
  .idiom-card {
    padding: clamp(1rem, 4vw, 1.5rem);
  }
  
  .options-container {
    grid-template-columns: 1fr;
    gap: 1rem;
  }
  
  .controls {
    flex-direction: column;
    gap: 1rem;
  }
  
  .modal-content {
    margin: 1rem;
    padding: clamp(1rem, 4vw, 1.5rem);
  }
  
  .modal-content h2 {
    font-size: clamp(1.3rem, 4vw, 1.8rem);
  }
  
  .modal-content p {
    font-size: clamp(1rem, 3vw, 1.3rem);
  }
}

@media (max-width: 480px) {
  .score-display {
    flex-direction: column;
    gap: 0.5rem;
    text-align: center;
  }
  
  .history-container {
    max-height: 100px;
  }
  
  .restart-button, .home-button {
    width: 100%;
    margin: 0.25rem 0;
  }
}

/* 适配电视屏幕 */
@media (min-width: 1920px) {
  .game-title {
    font-size: 3rem;
  }
  
  .idiom-text {
    font-size: 3rem;
  }
  
  .option-button, .control-button {
    font-size: 1.8rem;
  }
}
</style>